<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{TITLE}}</title>
    <script src="https://unpkg.com/mermaid@11.9.0/dist/mermaid.min.js"></script>
    <script src="https://unpkg.com/pako@2.1.0/dist/pako.min.js"></script>
    <style>
        :root {
            --sidebar-width: 280px;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
            color: #333;
        }

        .container {
            display: block;
            min-height: 100vh;
            position: relative;
        }

        .sidebar {
            width: var(--sidebar-width);
            background-color: #2c3e50;
            color: white;
            padding: 20px;
            overflow-y: auto;
            overflow-x: hidden;
            border-right: none;
            min-width: 200px;
            max-width: 500px;
            transition: transform 0.3s ease;
            position: fixed;
            top: 0;
            left: 0;
            height: 100vh;
            z-index: 1001;
        }

        .sidebar-resizer {
            position: fixed;
            top: 0;
            left: var(--sidebar-width);
            width: 4px;
            height: 100vh;
            background: transparent;
            cursor: col-resize;
            z-index: 1000;
        }
        
        .sidebar-resizer:hover,
        .sidebar-resizer.dragging {
            background: #007ACC;
        }

        .main-content {
            display: block;
            min-width: 0;
            transition: margin-left 0.3s ease;
            margin-left: var(--sidebar-width);
            overflow-y: auto;
            min-height: 100vh;
            padding: 20px;
            background-color: white;
        }

        .sidebar h1 {
            font-size: 20px;
            margin-bottom: 30px;
            margin-top: 20px;
            padding-bottom: 15px;
            padding-right: 50px;
            border-bottom: 2px solid #34495e;
            color: #ecf0f1;
            width: 100%;
            box-sizing: border-box;
            line-height: 28px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .nav-group {
            margin-bottom: 25px;
            width: 100%;
            box-sizing: border-box;
        }

        .nav-group h3 {
            font-size: 14px;
            color: #bdc3c7;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 1px;
            width: 100%;
            box-sizing: border-box;
        }

        .nav-item {
            display: block;
            padding: 12px 15px;
            margin-bottom: 5px;
            color: #ecf0f1;
            text-decoration: none;
            border-radius: 6px;
            transition: all 0.3s ease;
            cursor: pointer;
            font-size: 14px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            width: 100%;
            box-sizing: border-box;
        }

        .nav-item:hover {
            background-color: #34495e;
            transform: translateX(5px);
        }

        .nav-item.active {
            background-color: #3498db;
            color: white;
            font-weight: 600;
        }

        .nav-item.chain-item {
            padding-left: 25px;
            font-size: 13px;
            color: #bdc3c7;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            width: 100%;
            box-sizing: border-box;
        }

        .nav-item.chain-item:hover {
            background-color: #34495e;
            color: #ecf0f1;
        }

        .nav-item.chain-item.active {
            background-color: #e74c3c;
            color: white;
        }

        .content-header {
            margin-bottom: 12px;
            padding-bottom: 8px;
            border-bottom: 2px solid #ecf0f1;
        }

        .content-header h2 {
            color: #2c3e50;
            font-size: 20px;
            margin-bottom: 3px;
        }

        .content-header p {
            color: #7f8c8d;
            font-size: 13px;
        }

        .diagram-container {
            background-color: #fefefe;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            min-height: 200px;
            height: auto;
            text-align: center;
            overflow: visible;
            display: block;
        }

        .mermaid {
            display: block;
            margin: 0 auto;
            max-width: 100%;
            width: auto;
            height: auto !important;
            overflow: visible;
            min-height: 200px;
            box-sizing: border-box;
        }

        #diagramContent {
            width: 100%;
            height: auto;
            overflow: visible;
            display: block;
            box-sizing: border-box;
        }

        .mermaid svg {
            max-width: 100% !important;
            height: auto !important;
            width: auto !important;
            display: block;
            margin: 0 auto;
            box-sizing: border-box !important;
            max-height: 80vh;
        }

        .loading {
            text-align: center;
            padding: 60px;
            color: #7f8c8d;
        }

        .loading::before {
            content: '⏳';
            font-size: 24px;
            display: block;
            margin-bottom: 10px;
        }

        .error {
            background-color: #ffebee;
            color: #c62828;
            padding: 15px;
            border-radius: 6px;
            border-left: 4px solid #f44336;
        }

        .chain-counter {
            background-color: #3498db;
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 11px;
            margin-left: 10px;
            font-weight: bold;
        }

        .expand-toggle {
            float: right;
            font-size: 12px;
            cursor: pointer;
            color: #bdc3c7;
        }

        .expand-toggle:hover {
            color: #ecf0f1;
        }

        .mermaid-live-button {
            background: linear-gradient(135deg, #ff6b6b, #ee5a24);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            margin-top: 15px;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(238, 90, 36, 0.3);
        }

        .mermaid-live-button:hover {
            background: linear-gradient(135deg, #ee5a24, #e55039);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(238, 90, 36, 0.4);
        }

        .mermaid-live-button:active {
            transform: translateY(0);
            box-shadow: 0 2px 4px rgba(238, 90, 36, 0.3);
        }

        .diagram-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
        }

        .diagram-title-section {
            flex: 1;
        }

        .chains-collapsed .chain-item {
            display: none;
        }

        .chains-container {
            width: 100%;
            box-sizing: border-box;
        }

        /* 搜索框样式 */
        .search-container {
            margin-bottom: 20px;
            padding: 0 5px;
        }

        .search-box {
            width: 100%;
            padding: 10px 12px;
            border: 2px solid #34495e;
            border-radius: 6px;
            background-color: #34495e;
            color: #ecf0f1;
            font-size: 14px;
            transition: all 0.3s ease;
            outline: none;
        }

        .search-box::placeholder {
            color: #bdc3c7;
        }

        .search-box:focus {
            border-color: #3498db;
            background-color: #2c3e50;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }

        .search-results {
            margin-top: 10px;

        .search-result-item {
            padding: 8px 12px;
            margin-bottom: 3px;
            background-color: #2c3e50;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 13px;
            color: #ecf0f1;
            border-left: 3px solid transparent;
            height: 40px;
            display: flex;
            align-items: center;
            overflow: hidden;
        }

        .search-result-item:hover {
            background-color: #34495e;
            border-left-color: #3498db;
            transform: translateX(3px);
        }

        .search-result-item.highlight {
            background-color: #3498db;
            border-left-color: #2980b9;
        }

        .search-no-results {
            text-align: center;
            color: #7f8c8d;
            font-style: italic;
            padding: 20px;
        }

        .search-category {
            font-size: 11px;
            color: #95a5a6;
            margin-left: 8px;
            flex-shrink: 0; /* 分类标签不收缩 */
            white-space: nowrap;
        }

        .search-category-header {
            font-size: 12px;
            font-weight: bold;
            color: #3498db;
            margin: 8px 0 4px 0;
            padding: 4px 8px;
            border-bottom: 1px solid #34495e;
        }

        .search-item-main {
            display: flex;
            align-items: center;
            width: 100%;
            min-width: 0; /* 允许 flex 子元素收缩 */
        }

        .search-item-icon {
            margin-right: 8px;
            font-size: 14px;
            flex-shrink: 0; /* 图标不收缩 */
        }

        .search-item-name {
            flex: 1;
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            min-width: 0; /* 允许文本收缩 */
        }

        .search-item-name mark {
            background-color: #f39c12;
            color: #2c3e50;
            padding: 1px 2px;
            border-radius: 2px;
        }

        .search-item-fullname {
            font-size: 11px;
            color: #95a5a6;
            margin-top: 2px;
            padding-left: 22px;
        }

        .search-item-fullname mark {
            background-color: #f39c12;
            color: #2c3e50;
            padding: 1px 2px;
            border-radius: 2px;
        }

        .search-item-charts {
            font-size: 10px;
            color: #7f8c8d;
            margin-top: 2px;
            padding-left: 22px;
            font-style: italic;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }
            
            .sidebar {
                width: 100%;
                height: auto;
                max-height: 40vh;
            }
            
            .main-content {
                flex: 1;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="sidebar" id="sidebar">
            <div class="sidebar-resizer" id="sidebarResizer"></div>
            
            <h1>{{TITLE}}</h1>
            
            <!-- 搜索框 -->
            <div class="search-container">
                <input type="text" id="searchBox" class="search-box" placeholder="搜索图表或元素..." oninput="performSearch()">
                <div id="searchResults" class="search-results" style="display: none;"></div>
            </div>
            
            <div class="nav-group">
                <h3>图表展示</h3>
                <a class="nav-item" data-diagram="Statistics" href="#Statistics" title="📊 统计信息">
                    📊 统计信息
                </a>
                <a class="nav-item" data-diagram="ArchitectureOverview" href="#ArchitectureOverview" title="🏛️ 总览图">
                    🏛️ 总览图
                </a>
            </div>

            <div class="nav-group">
                <h3>聚合关系图 <span class="expand-toggle" onclick="toggleAggregateDiagrams()">▶</span> <span class="chain-counter" id="aggregateDiagramCounter"></span></h3>
                <div class="chains-container" id="aggregateDiagramsContainer">
                    <!-- 动态生成的聚合关系图菜单 -->
                </div>
            </div>

            <div class="nav-group">
                <h3>处理流程图 <span class="expand-toggle" onclick="toggleProcessingFlow()">▶</span> <span class="chain-counter" id="processingFlowCounter">0</span></h3>
                <div class="chains-container" id="processingFlowContainer">
                    <!-- 动态生成的处理流程图将在这里显示 -->
                </div>
            </div>
        </div>

        <div class="main-content">
            <div class="content-header">
                <div class="diagram-header">
                    <div class="diagram-title-section">
                        <h2 id="diagramTitle">选择图表类型</h2>
                        <p id="diagramDescription">请从左侧菜单选择要查看的图表类型</p>
                    </div>
                    <div class="diagram-actions">
                        <button id="mermaidLiveButton" class="mermaid-live-button" style="display: none;" onclick="openInMermaidLive()">
                            🔗 View in Mermaid Live
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="diagram-container">
                <div id="diagramContent">
                    <div class="loading">正在加载图表数据...</div>
                </div>
            </div>
        </div>
    </div>
    <script>
        // 搜索功能实现
        function performSearch() {
            const query = document.getElementById('searchBox').value.trim().toLowerCase();
            const resultsDiv = document.getElementById('searchResults');
            if (!query) {
                resultsDiv.style.display = 'none';
                resultsDiv.innerHTML = '';
                return;
            }
            
            // 增强搜索逻辑：支持搜索图表名称和包含的元素名称
            const results = allSearchableItems.filter(item => {
                // 搜索图表名称
                const nameMatch = item.name && item.name.toLowerCase().includes(query);
                
                // 搜索包含的元素名称
                const termsMatch = item.searchableTerms && item.searchableTerms.some(term => 
                    term && term.toLowerCase().includes(query)
                );
                
                return nameMatch || termsMatch;
            });
            
            if (results.length === 0) {
                resultsDiv.innerHTML = '<div class="search-no-results">未找到相关内容</div>';
                resultsDiv.style.display = 'block';
                return;
            }
            
            // 直接显示搜索结果，不进行分组
            let html = '';
            results.forEach(item => {
                const displayName = highlightSearchTerm(item.name, query);
                
                html += `
                    <div class="search-result-item" onclick="selectSearchResult(allSearchableItems[${allSearchableItems.indexOf(item)}])" title="${escapeHtml(item.name)}">
                        <div class="search-item-main">
                            <span class="search-item-icon">${item.icon}</span>
                            <span class="search-item-name">${displayName}</span>
                            <span class="search-category">${item.category}</span>
                        </div>
                    </div>
                `;
            });
            
            resultsDiv.innerHTML = html;
            resultsDiv.style.display = 'block';
        }
        
        // 高亮搜索词
        function highlightSearchTerm(text, query) {
            if (!text || !query) return text;
            const regex = new RegExp(`(${escapeRegExp(query)})`, 'gi');
            return text.replace(regex, '<mark>$1</mark>');
        }
        
        // 转义正则表达式特殊字符
        function escapeRegExp(string) {
            return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        }
        
        // HTML转义函数
        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        // 初始化 Mermaid
        mermaid.initialize({
            startOnLoad: false,
            maxEdges: {{MAX_EDGES}},
            maxTextSize: {{MAX_TEXT_SIZE}},
            theme: 'base',
            themeVariables: {
                primaryColor: '#3498db',
                primaryTextColor: '#2c3e50',
                primaryBorderColor: '#2980b9',
                lineColor: '#34495e',
                secondaryColor: '#ecf0f1',
                tertiaryColor: '#bdc3c7',
                background: '#ffffff',
                mainBkg: '#ffffff',
                secondBkg: '#f8f9fa',
                tertiaryBkg: '#ecf0f1'
            },
            flowchart: {
                htmlLabels: true,
                curve: 'basis',
                diagramPadding: 20,
                useMaxWidth: false,
                useMaxHeight: false,
                nodeSpacing: 30,
                rankSpacing: 30
            },
            classDiagram: {
                htmlLabels: true,
                diagramPadding: 20,
                useMaxWidth: false,
                useMaxHeight: false
            }
        });

        // 图表配置
        const diagramConfigs = {{DIAGRAM_CONFIGS}};
        
        // 统计数据
        const statistics = {{STATISTICS}};
        
        // 分析结果数据
        const analysisResult = {{ANALYSIS_RESULT}};
        
        // Mermaid图表数据
        const diagrams = {{DIAGRAMS}};

        // 单独的链路流程图数据
        const allChainFlowCharts = {{ALL_CHAIN_FLOW_CHARTS}};

        // 所有聚合关系图数据
        const allAggregateRelationDiagrams = {{ALL_AGGREGATE_RELATION_DIAGRAMS}};

        let currentDiagram = null;
        let currentDiagramData = null;
        let processingFlowExpanded = false;
        let aggregateDiagramsExpanded = false;

        // 初始化页面
        function initializePage() {
            generateAggregateDiagramNavigation();
            generateChainNavigation();
            addNavigationListeners();
            addHashChangeListener();
            handleInitialHash();
        }

        // 生成聚合关系图导航
        function generateAggregateDiagramNavigation() {
            const container = document.getElementById('aggregateDiagramsContainer');
            const counter = document.getElementById('aggregateDiagramCounter');
            if (container && counter) {
                container.innerHTML = '';
                counter.textContent = allAggregateRelationDiagrams.length;
                container.classList.add('chains-collapsed');
                allAggregateRelationDiagrams.forEach((agg, index) => {
                    const aggItem = document.createElement('a');
                    aggItem.className = 'nav-item chain-item';
                    aggItem.setAttribute('data-aggregate-diagram', index);
                    const aggId = encodeURIComponent(agg.name.replace(/[^a-zA-Z0-9一-龥]/g, '-'));
                    aggItem.href = `#aggregate-diagram-${aggId}`;
                    aggItem.textContent = `🗂️ ${agg.name}`;
                    aggItem.title = `🗂️ ${agg.name}`;
                    container.appendChild(aggItem);
                });
            }
        }

        // 生成命令链路导航
        function generateChainNavigation() {
            // 处理流程图导航
            const processingContainer = document.getElementById('processingFlowContainer');
            const processingCounter = document.getElementById('processingFlowCounter');
            if (processingContainer && processingCounter) {
                processingContainer.innerHTML = '';
                processingCounter.textContent = allChainFlowCharts.length;
                
                // 默认设置为折叠状态
                processingContainer.classList.add('chains-collapsed');
                allChainFlowCharts.forEach((chain, index) => {
                    const chainItem = document.createElement('a');
                    chainItem.className = 'nav-item chain-item';
                    chainItem.setAttribute('data-processing-flow', index);
                    const chainId = encodeURIComponent(chain.name.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '-'));
                    chainItem.href = `#processing-flow-${chainId}`;
                    chainItem.textContent = `🔄 ${chain.name}`;
                    chainItem.title = `🔄 ${chain.name}`;
                    processingContainer.appendChild(chainItem);
                });
            }
        }

        // 添加导航事件监听
        function addNavigationListeners() {
            document.querySelectorAll('.nav-item[data-diagram]').forEach(item => {
                item.addEventListener('click', (e) => {
                    e.preventDefault();
                    const diagramType = item.getAttribute('data-diagram');
                    showDiagram(diagramType);
                });
            });
            document.querySelectorAll('.nav-item[data-aggregate-diagram]').forEach(item => {
                item.addEventListener('click', (e) => {
                    e.preventDefault();
                    const aggIndex = parseInt(item.getAttribute('data-aggregate-diagram'));
                    if (!aggregateDiagramsExpanded) {
                        toggleAggregateDiagrams();
                    }
                    showAggregateDiagram(aggIndex);
                });
            });
            // 处理流程图监听
            document.querySelectorAll('.nav-item.chain-item[data-processing-flow]').forEach(item => {
                item.addEventListener('click', (e) => {
                    e.preventDefault();
                    const chainIndex = parseInt(item.getAttribute('data-processing-flow'));
                    if (!isNaN(chainIndex)) {
                        showRequestChain(chainIndex);
                    }
                });
            });
        }

        // 显示图表
        async function showDiagram(diagramType, updateHash = true) {
            const config = diagramConfigs[diagramType];
            if (!config) return;

            if (updateHash) {
                window.location.hash = diagramType;
            }

            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            document.querySelector(`[data-diagram="${diagramType}"]`).classList.add('active');

            document.getElementById('diagramTitle').textContent = config.title;
            document.getElementById('diagramDescription').textContent = config.description;
            hideMermaidLiveButton();

            const contentDiv = document.getElementById('diagramContent');
            
            // 特殊处理统计信息页面
            if (diagramType === 'Statistics') {
                showStatistics(contentDiv);
                return;
            }
            
            contentDiv.innerHTML = '<div class="loading">正在生成图表...</div>';

            try {
                await new Promise(resolve => setTimeout(resolve, 300));
                const diagramData = diagrams[diagramType];
                if (!diagramData) {
                    throw new Error('图表数据不存在');
                }
                await renderMermaidDiagram(diagramData, contentDiv);
                currentDiagram = diagramType;
                currentDiagramData = diagramData;
                showMermaidLiveButton();
            } catch (error) {
                console.error('生成图表失败:', error);
                const diagramData = diagrams[diagramType];
                contentDiv.innerHTML = `<div class="error">${formatErrorMessage('生成图表失败', error)}</div>`;
                currentDiagram = diagramType;
                currentDiagramData = diagramData || '';
                showMermaidLiveButton();
            }
        }


        // 渲染Mermaid图表
        async function renderMermaidDiagram(diagramData, container) {
            const diagramId = `diagram-${Date.now()}`;
            
            try {
                container.innerHTML = '';
                const diagramElement = document.createElement('div');
                diagramElement.id = diagramId;
                diagramElement.className = 'mermaid';
                diagramElement.textContent = diagramData;
                container.appendChild(diagramElement);
                await mermaid.run({ nodes: [diagramElement] });
            } catch (error) {
                console.error('Mermaid渲染失败:', error);
                // 确保在错误时也设置当前图表数据，这样按钮可以正常显示
                currentDiagramData = diagramData;
                throw error;
            }
        }

        // 显示处理流程图
        async function showRequestChain(chainIndex, updateHash = true) {
            const chain = allChainFlowCharts[chainIndex];
            if (!chain) return;

            // 如果处理流程图菜单是折叠的，则展开它
            if (!processingFlowExpanded) {
                toggleProcessingFlow();
            }

            if (updateHash) {
                const chainId = encodeURIComponent(chain.name.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '-'));
                window.location.hash = `processing-flow-${chainId}`;
            }

            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            document.querySelector(`[data-processing-flow="${chainIndex}"]`).classList.add('active');

            document.getElementById('diagramTitle').textContent = `${chain.name}`;
            document.getElementById('diagramDescription').textContent = '处理流程图：展示单个请求的完整流转过程';
            hideMermaidLiveButton();

            const contentDiv = document.getElementById('diagramContent');
            contentDiv.innerHTML = '<div class="loading">正在生成处理流程图...</div>';

            try {
                setTimeout(function() {
                    renderMermaidDiagram(chain.diagram, contentDiv).then(() => {
                        currentDiagram = `processing-flow-${chainIndex}`;
                        currentDiagramData = chain.diagram;
                        showMermaidLiveButton();
                    }).catch(error => {
                        console.error('生成处理流程图失败:', error);
                        contentDiv.innerHTML = `<div class="error">${formatErrorMessage('生成处理流程图失败', error)}</div>`;
                        currentDiagram = `processing-flow-${chainIndex}`;
                        currentDiagramData = chain.diagram;
                        showMermaidLiveButton();
                    });
                }, 200);
            } catch (error) {
                console.error('生成处理流程图失败:', error);
                contentDiv.innerHTML = `<div class="error">${formatErrorMessage('生成处理流程图失败', error)}</div>`;
                currentDiagram = `processing-flow-${chainIndex}`;
                currentDiagramData = chain.diagram;
                showMermaidLiveButton();
            }
        }


        // 格式化错误信息
        function formatErrorMessage(prefix, error) {
            let message = error.message;
            if (message && message.toLowerCase().includes('too many edges')) {
                return `${prefix}: ${message}。图表过于复杂，请点击 "🔗 View in Mermaid Live" 按钮在 Mermaid Live 中查看完整图表。`;
            }
            return `${prefix}: ${message}`;
        }

        // 显示 Mermaid Live 按钮
        function showMermaidLiveButton() {
            const button = document.getElementById('mermaidLiveButton');
            if (button) {
                button.style.display = 'inline-flex';
            }
        }

        // 隐藏 Mermaid Live 按钮
        function hideMermaidLiveButton() {
            const button = document.getElementById('mermaidLiveButton');
            if (button) {
                button.style.display = 'none';
            }
        }

        // 在 Mermaid Live 中打开当前图表
        function openInMermaidLive() {
            if (!currentDiagramData) {
                alert('没有可用的图表数据');
                return;
            }

            try {
                // 检查是否有 pako 库可用
                if (typeof pako !== 'undefined') {
                    // 使用 pako 压缩方式 (首选)
                    const state = {
                        code: currentDiagramData,
                        mermaid: {
                            theme: 'default',
                            maxEdges: {{MAX_EDGES}},
                            maxTextSize: {{MAX_TEXT_SIZE}}
                        },
                        autoSync: true,
                        updateDiagram: true
                    };

                    const stateString = JSON.stringify(state);
                    const compressed = pako.deflate(stateString, { to: 'string' });
                    const encoded = btoa(String.fromCharCode.apply(null, compressed));
                    const mermaidLiveUrl = `https://mermaid.live/edit#pako:${encoded}`;

                    window.open(mermaidLiveUrl, '_blank');
                } else {
                    // 回退到 base64 编码方式
                    const encodedDiagram = btoa(unescape(encodeURIComponent(currentDiagramData)));
                    const mermaidLiveUrl = `https://mermaid.live/edit#base64:${encodedDiagram}`;
                    window.open(mermaidLiveUrl, '_blank');
                }
            } catch (error) {
                console.error('无法打开 Mermaid Live:', error);
                // 如果编码失败，尝试直接传递代码
                try {
                    const simpleEncodedDiagram = btoa(currentDiagramData);
                    const fallbackUrl = `https://mermaid.live/edit#base64:${simpleEncodedDiagram}`;
                    window.open(fallbackUrl, '_blank');
                } catch (fallbackError) {
                    console.error('备用方案也失败:', fallbackError);
                    alert('无法打开 Mermaid Live，请检查浏览器控制台');
                }
            }
        }

        // 显示统计信息页面
        function showStatistics(container) {
            const nodeTypeCounts = statistics.nodeStats;
            const relationshipTypeCounts = statistics.relationshipStats;
            
            // 定义要显示的节点类型（按定义顺序，排除指定类型）
            const displayNodeTypes = [
                'Controller',
                'Endpoint', 
                'CommandSender',
                'Command',
                'CommandHandler',
                'Aggregate',
                'DomainEvent',
                'IntegrationEvent',
                'DomainEventHandler',
                'IntegrationEventHandler',
                'IntegrationEventConverter'
            ];
            
            // 定义要显示的关系类型（按定义顺序，排除指定类型）
            const displayRelationshipTypes = [
                'ControllerToCommand',
                'EndpointToCommand',
                'CommandSenderToCommand',
                'CommandToAggregate',
                'AggregateToDomainEvent',
                'DomainEventToHandler',
                'DomainEventHandlerToCommand',
                'IntegrationEventToHandler',
                'IntegrationEventHandlerToCommand',
                'DomainEventToIntegrationEvent'
            ];
            
            // 计算过滤后的总数
            const filteredNodeCount = displayNodeTypes.reduce((sum, type) => sum + (nodeTypeCounts[type] || 0), 0);
            const filteredRelationshipCount = displayRelationshipTypes.reduce((sum, type) => sum + (relationshipTypeCounts[type] || 0), 0);
            
            let html = '<div style="padding: 15px; font-family: \'Segoe UI\', Tahoma, Geneva, Verdana, sans-serif; height: calc(100vh - 140px); overflow-y: auto;">';
            
            // 总体统计 - 更紧凑的设计
            html += '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">';
            html += '<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; border-radius: 8px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">';
            html += '<span style="font-size: 16px; font-weight: 600;">总元素数</span>';
            html += `<span style="font-size: 28px; font-weight: bold;">${filteredNodeCount}</span>`;
            html += '</div>';
            html += '<div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; padding: 15px; border-radius: 8px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">';
            html += '<span style="font-size: 16px; font-weight: 600;">总关系数</span>';
            html += `<span style="font-size: 28px; font-weight: bold;">${filteredRelationshipCount}</span>`;
            html += '</div>';
            html += '</div>';
            
            // 两列布局 - 左侧元素统计，右侧关系统计
            html += '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; height: calc(100vh - 260px);">';
            
            // 元素统计
            html += '<div style="background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); overflow-y: auto;">';
            html += '<h2 style="margin: 0 0 15px 0; color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 8px; font-size: 18px;">📊 元素统计</h2>';
            html += '<div style="display: grid; gap: 8px;">';
            
            // 按定义顺序显示节点类型
            displayNodeTypes.forEach(type => {
                const count = nodeTypeCounts[type] || 0;
                if (count > 0) {
                    const percentage = ((count / filteredNodeCount) * 100).toFixed(1);
                    html += '<div style="background: #f8f9fa; padding: 8px 12px; border-radius: 6px; border-left: 3px solid #3498db; display: flex; justify-content: space-between; align-items: center; min-height: 32px;">';
                    html += `<div style="font-weight: 600; color: #2c3e50; font-size: 14px;">${type}</div>`;
                    html += '<div style="display: flex; align-items: center; gap: 12px;">';
                    html += `<div style="font-size: 16px; font-weight: bold; color: #e74c3c;">${count}</div>`;
                    html += `<div style="font-size: 11px; color: #7f8c8d; min-width: 35px;">${percentage}%</div>`;
                    html += '</div>';
                    html += '</div>';
                }
            });
            html += '</div></div>';
            
            // 关系统计
            html += '<div style="background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); overflow-y: auto;">';
            html += '<h2 style="margin: 0 0 15px 0; color: #2c3e50; border-bottom: 2px solid #e74c3c; padding-bottom: 8px; font-size: 18px;">🔗 关系统计</h2>';
            html += '<div style="display: grid; gap: 8px;">';
            
            // 按定义顺序显示关系类型
            displayRelationshipTypes.forEach(type => {
                const count = relationshipTypeCounts[type] || 0;
                if (count > 0) {
                    const percentage = ((count / filteredRelationshipCount) * 100).toFixed(1);
                    html += '<div style="background: #f8f9fa; padding: 8px 12px; border-radius: 6px; border-left: 3px solid #e74c3c; display: flex; justify-content: space-between; align-items: center; min-height: 32px;">';
                    html += `<div style="font-weight: 600; color: #2c3e50; font-size: 14px;">${type}</div>`;
                    html += '<div style="display: flex; align-items: center; gap: 12px;">';
                    html += `<div style="font-size: 16px; font-weight: bold; color: #3498db;">${count}</div>`;
                    html += `<div style="font-size: 11px; color: #7f8c8d; min-width: 35px;">${percentage}%</div>`;
                    html += '</div>';
                    html += '</div>';
                }
            });
            html += '</div></div>';
            
            html += '</div></div>';
            
            container.innerHTML = html;
        }

        // 切换单独链路展开/收起
        function toggleProcessingFlow() {
            processingFlowExpanded = !processingFlowExpanded;
            const container = document.getElementById('processingFlowContainer');
            const toggles = document.querySelectorAll('.expand-toggle');
            const processingToggle = toggles[1]; // 第二个展开/收起按钮
            
            if (processingFlowExpanded) {
                container.classList.remove('chains-collapsed');
                if (processingToggle) processingToggle.textContent = '▼';
            } else {
                container.classList.add('chains-collapsed');
                if (processingToggle) processingToggle.textContent = '▶';
            }
        }

        // 切换聚合关系图展开/收起
        function toggleAggregateDiagrams() {
            aggregateDiagramsExpanded = !aggregateDiagramsExpanded;
            const container = document.getElementById('aggregateDiagramsContainer');
            const toggles = document.querySelectorAll('.expand-toggle');
            const aggToggle = toggles[0]; // 第一个展开/收起按钮
            if (aggregateDiagramsExpanded) {
                container.classList.remove('chains-collapsed');
                if (aggToggle) aggToggle.textContent = '▼';
            } else {
                container.classList.add('chains-collapsed');
                if (aggToggle) aggToggle.textContent = '▶';
            }
        }

        // 添加URL哈希变化监听
        function addHashChangeListener() {
            window.addEventListener('hashchange', handleHashChange);
        }

        // 根据聚合名称查找索引
        function findAggregateIndexByName(aggName, aggArray) {
            const decodedName = decodeURIComponent(aggName).replace(/-/g, ' ');
            for (let i = 0; i < aggArray.length; i++) {
                const normalizedAggName = aggArray[i].name.replace(/[^a-zA-Z0-9一-龥]/g, '-');
                if (normalizedAggName === aggName || aggArray[i].name === decodedName) {
                    return i;
                }
            }
            return -1;
        }

        // 处理URL哈希变化
        function handleHashChange() {
            const hash = window.location.hash.substring(1);
            if (!hash) return;
            if (diagramConfigs[hash]) {
                showDiagram(hash, false);
                return;
            }
            if (hash.startsWith('aggregate-diagram-')) {
                const aggName = hash.substring(18);
                let aggIndex = findAggregateIndexByName(aggName, allAggregateRelationDiagrams);
                if (aggIndex === -1) {
                    aggIndex = parseInt(aggName);
                }
                if (!isNaN(aggIndex) && aggIndex >= 0 && aggIndex < allAggregateRelationDiagrams.length) {
                    showAggregateDiagram(aggIndex, false);
                    return;
                }
            }
            if (hash.startsWith('processing-flow-')) {
                const chainName = hash.substring(16);
                let chainIndex = -1;
                for (let i = 0; i < allChainFlowCharts.length; i++) {
                    const normalizedChainName = encodeURIComponent(allChainFlowCharts[i].name.replace(/[^a-zA-Z0-9]/g, '-'));
                    if (normalizedChainName === chainName) {
                        chainIndex = i;
                        break;
                    }
                }
                if (chainIndex === -1) {
                    chainIndex = parseInt(chainName);
                }
                if (!isNaN(chainIndex) && chainIndex >= 0 && chainIndex < allChainFlowCharts.length) {
                    showRequestChain(chainIndex, false);
                    return;
                }
            }
        }

        // 处理初始URL哈希
        function handleInitialHash() {
            const hash = window.location.hash.substring(1);
            if (hash) {
                handleHashChange();
            } else {
                showDiagram('Statistics', false);
            }
        }

        // 搜索功能
        let allSearchableItems = [];

        // 初始化搜索数据
        function initializeSearchData() {
            allSearchableItems = [];
            
            // 添加聚合关系图（与菜单一一对应）
            allAggregateRelationDiagrams.forEach((agg, index) => {
                const aggId = encodeURIComponent(agg.name.replace(/[^a-zA-Z0-9一-龥]/g, '-'));
                
                // 简单直接：将图表名称和图表内容都作为搜索内容
                const searchableTerms = [agg.name];
                
                // 如果图表有内容（diagram文本），也加入搜索范围
                if (agg.diagram) {
                    searchableTerms.push(agg.diagram);
                }
                
                allSearchableItems.push({
                    name: agg.name,
                    type: 'aggregateDiagram',
                    category: '聚合关系图',
                    icon: '🗂️',
                    target: `aggregate-diagram-${aggId}`,
                    index: index,
                    searchableTerms: searchableTerms
                });
            });
            
            // 添加处理流程图（与菜单一一对应）
            allChainFlowCharts.forEach((chain, index) => {
                const chainId = encodeURIComponent(chain.name.replace(/[^a-zA-Z0-9一-龥]/g, '-'));
                
                // 简单直接：将图表名称和图表内容都作为搜索内容
                const searchableTerms = [chain.name];
                
                // 如果图表有内容（diagram文本），也加入搜索范围
                if (chain.diagram) {
                    searchableTerms.push(chain.diagram);
                }
                
                allSearchableItems.push({
                    name: chain.name,
                    type: 'processingFlow',
                    category: '处理流程图',
                    icon: '🔄',
                    target: `processing-flow-${chainId}`,
                    index: index,
                    searchableTerms: searchableTerms
                });
            });
        }
        
        // 根据节点类型获取图标
        function getIconForNodeType(nodeType) {
            const iconMap = {
                'Controller': '🎮',
                'Service': '⚙️',
                'Repository': '🗄️',
                'Entity': '📦',
                'Aggregate': '🏛️',
                'Command': '⚡',
                'Query': '🔍',
                'Event': '📡',
                'Handler': '🛠️',
                'Interface': '🔌',
                'Class': '📄',
                'Enum': '📝',
                'Value': '💎'
            };
            return iconMap[nodeType] || '📄';
        }

        function selectSearchResult(item) {
            document.getElementById('searchResults').style.display = 'none';
            document.getElementById('searchBox').value = '';
            
            switch (item.type) {
                case 'aggregateDiagram':
                    // 直接调用显示函数，它会处理展开和激活
                    showAggregateDiagram(item.index);
                    break;
                case 'processingFlow':
                    // 直接调用显示函数，它会处理展开和激活
                    showRequestChain(item.index);
                    break;
            }
        }
        
        // 在图表中高亮显示元素（这个功能需要根据Mermaid的API来实现）
        function highlightElementInDiagram(nodeId) {
            // 这里可以添加高亮逻辑，比如滚动到元素位置、改变元素颜色等
            // 由于Mermaid图表的限制，这个功能可能需要更复杂的实现
            console.log('Highlighting element:', nodeId);
        }

        // 点击页面其他地方隐藏搜索结果
        document.addEventListener('click', function(event) {
            const searchContainer = document.querySelector('.search-container');
            if (!searchContainer.contains(event.target)) {
                document.getElementById('searchResults').style.display = 'none';
            }
        });

        // 键盘导航支持
        document.getElementById('searchBox').addEventListener('keydown', function(event) {
            const searchResults = document.getElementById('searchResults');
            const resultItems = searchResults.querySelectorAll('.search-result-item');

            if (event.key === 'Escape') {
                searchResults.style.display = 'none';
                this.value = '';
                return;
            }

            if (event.key === 'Enter' && resultItems.length > 0) {
                const highlighted = searchResults.querySelector('.search-result-item.highlight');
                if (highlighted) {
                    highlighted.click();
                } else {
                    resultItems[0].click();
                }
                return;
            }

            if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
                event.preventDefault();
                const highlighted = searchResults.querySelector('.search-result-item.highlight');
                let nextIndex = 0;

                if (highlighted) {
                    highlighted.classList.remove('highlight');
                    const currentIndex = Array.from(resultItems).indexOf(highlighted);
                    if (event.key === 'ArrowDown') {
                        nextIndex = (currentIndex + 1) % resultItems.length;
                    } else {
                        nextIndex = (currentIndex - 1 + resultItems.length) % resultItems.length;
                    }
                }

                if (resultItems[nextIndex]) {
                    resultItems[nextIndex].classList.add('highlight');
                }
            }
        });

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializePage();
            initializeSearchData();
            initializeSidebar();
        });
        
        // 侧边栏功能
        let sidebarWidth = 280;
        let isDragging = false;
        
        function initializeSidebar() {
            const sidebar = document.getElementById('sidebar');
            const resizer = document.getElementById('sidebarResizer');
            
            // 初始化CSS变量
            document.documentElement.style.setProperty('--sidebar-width', sidebarWidth + 'px');
            // 初始化拖拽线位置
            resizer.style.left = `${sidebarWidth}px`;
            
            // 拖拽调整宽度
            resizer.addEventListener('mousedown', initResize);
            
            function initResize(e) {
                isDragging = true;
                resizer.classList.add('dragging');
                document.addEventListener('mousemove', doResize);
                document.addEventListener('mouseup', stopResize);
                document.body.style.cursor = 'col-resize';
                document.body.style.userSelect = 'none';
            }
            
            function doResize(e) {
                if (!isDragging) return;
                
                const newWidth = e.clientX;
                if (newWidth >= 200 && newWidth <= 500) {
                    sidebarWidth = newWidth;
                    sidebar.style.width = newWidth + 'px';
                    // 更新CSS变量
                    document.documentElement.style.setProperty('--sidebar-width', newWidth + 'px');
                    // 更新拖拽线位置
                    resizer.style.left = `${newWidth}px`;
                    
                    // 强制重绘所有子元素
                    const allItems = sidebar.querySelectorAll('.nav-item');
                    allItems.forEach(item => {
                        item.style.width = '100%';
                    });
                }
            }
            
            function stopResize() {
                isDragging = false;
                resizer.classList.remove('dragging');
                document.removeEventListener('mousemove', doResize);
                document.removeEventListener('mouseup', stopResize);
                document.body.style.cursor = '';
                document.body.style.userSelect = '';
            }
        }
        window.showAggregateDiagram = showAggregateDiagram;
        // 显示聚合关系图
        async function showAggregateDiagram(aggIndex, updateHash = true) {
            const agg = allAggregateRelationDiagrams[aggIndex];
            if (!agg) return;

            if (!aggregateDiagramsExpanded) {
                toggleAggregateDiagrams();
            }

            if (updateHash) {
                const aggId = encodeURIComponent(agg.name.replace(/[^a-zA-Z0-9一-龥]/g, '-'));
                window.location.hash = `aggregate-diagram-${aggId}`;
            }

            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            document.querySelector(`[data-aggregate-diagram="${aggIndex}"]`).classList.add('active');

            document.getElementById('diagramTitle').textContent = `${agg.name}`;
            document.getElementById('diagramDescription').textContent = '聚合根相关的关系图';
            hideMermaidLiveButton();

            const contentDiv = document.getElementById('diagramContent');
            contentDiv.innerHTML = '<div class="loading">正在生成聚合关系图...</div>';

            try {
                setTimeout(function() {
                    renderMermaidDiagram(agg.diagram, contentDiv).then(() => {
                        currentDiagram = `aggregate-diagram-${aggIndex}`;
                        currentDiagramData = agg.diagram;
                        showMermaidLiveButton();
                    }).catch(error => {
                        console.error('生成聚合关系图失败:', error);
                        contentDiv.innerHTML = `<div class="error">${formatErrorMessage('生成聚合关系图失败', error)}</div>`;
                        currentDiagram = `aggregate-diagram-${aggIndex}`;
                        currentDiagramData = agg.diagram;
                        showMermaidLiveButton();
                    });
                }, 200);
            } catch (error) {
                console.error('生成聚合关系图失败:', error);
                contentDiv.innerHTML = `<div class="error">${formatErrorMessage('生成聚合关系图失败', error)}</div>`;
                currentDiagram = `aggregate-diagram-${aggIndex}`;
                currentDiagramData = agg.diagram;
                showMermaidLiveButton();
            }
        }
    </script>
</body>
</html>
